<?php

namespace app\api\controller;

use app\common\lib\Param;
use app\common\lib\Show;
use app\common\lib\Str;
use app\Request;
use think\facade\Cache;
use think\response\Json;

class ApplyRepair extends AuthBase
{

    public function save(): Json
    {
        if (!$this->request->isPost()) {
            return Show::error([],"非法请求");
        }

        $category_id = input("category_id", 0, "intval");
        $contact_person = $this->request->param("contact_person", "", "trim");
        $contact_phone = $this->request->param("contact_phone", "", "trim");
        $address = $this->request->param("address", "", "trim");
        $longitude = $this->request->param("longitude", "", "trim");
        $latitude = $this->request->param("latitude", "", "trim");
        $detail = $this->request->param("detail", "", "trim");
        $content = $this->request->param("content", "", "trim");

        //参数校验
        $data = [
            'category_id' => $category_id,
            'contact_person' => $contact_person,
            'contact_phone' => $contact_phone,
            'address' => $address,
            'longitude' => $longitude,
            'latitude' => $latitude,
            'detail' => $detail,
            'content' => $content,
        ];
        $validate = new \app\api\validate\ApplyRepair();
        if (!$validate->scene('save')->check($data)) {
            return Show::error([], $validate->getError());
        }

        try {
            $result = (new \app\common\business\ApplyRepair())->saveData($this->userId,$data);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "保存成功");
        }
        return Show::error([], '保存失败');
    }

    //我的报修申请分页列表
    public function index(){
        list($page,$limit) = Param::getMore([
            ['page', 1],
            ['limit', 10],
        ], $this->request, true);

        $applyBis = new \app\common\business\ApplyRepair();

        //筛选条件
        $where = [['user_id','=',$this->userId]];
        $list = $applyBis->getListByWhere($where,$page,$limit,'id,type,category_id,contact_person,contact_phone,address,deal_status,create_time');
        $totalCount = $applyBis->getCountByWhere($where,'id');
        if (!empty($list)) {$list = $applyBis->resetInfo($list);}//reset

        $result = [
            'count'=>$totalCount,
            'list'=>$list
        ];
        return Show::success($result);
    }

    public function detail()
    {
        $id = input("id", 0, "intval");

        $applyBis = new \app\common\business\ApplyRepair();

        //筛选条件
        $where = [
            ['id','=',$id],
            ['user_id','=',$this->userId]
        ];
        $info = $applyBis->getNormalByWhere($where);
        if (empty($info)) return Show::error([],'数据不存在');
        return Show::success($info);
    }
}
